package com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor.base;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.json.JSONObject;

import com.romotc.qqrobot.bean.QQLogedin;
import com.romotc.qqrobot.webqq.SysConstant;
import com.romotc.qqrobot.webqq.WebQQConstant;
import com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor.DateProcessor;
import com.romotc.scache.RequestSpy;

/**
 * 验证码接口返回数据处理基础类
 * @author romotc
 *
 */
public abstract class GetImage_BaseProcessor implements DateProcessor {
	public static final String Key_ImageFilePath = "GetImage_Processor_New_out_imageFilePath";
	private static final String Key_Image_VCode = "GetImage_Processor_New_out_imageVCode";

	public abstract String processResFile(File resFile) ;
	
	@Override
	public JSONObject processResponse(QQLogedin loginQQ, RequestSpy rqSpy,
			JSONObject reqDataObj) throws Exception {
		String s = rqSpy.cacheFile;
		String resFilePath = "";
		if(StringUtils.isBlank(s)) {
			System.out.println("GetImage_Processor_New：未返回图片");
		}else {
			File resFile = new File(s);
			if(resFile.exists() && resFile.length() > 10) {
				//保存文件到指定目录
				int aid = reqDataObj.optInt(WebQQConstant.Key_ReqDataObj_AID);
				resFile = reStoteResFile(resFile, aid);
				
				//进行处理
				String result = processResFile(resFile);
				reqDataObj.put(Key_Image_VCode, result);
			}
		}
		return reqDataObj;
	}


	/**
	 * 处理返回的文件 主要用户保存到另外一个目录
	 * @param file
	 * @return 文件处理结果
	 */
	public File reStoteResFile(File cacheFile, int aid) throws IOException {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		String curDay = fmt.format(new Date());
		
		String savePath = SysConstant.vcodeStoreFolder;
		if(aid > 0) 
			savePath += File.separator + aid;
		savePath += File.separator + curDay;
		
		//创建目录
		File vcodeFile = new File(savePath);
		if(vcodeFile.exists() && vcodeFile.isFile()) 
			vcodeFile.delete();
		if(!vcodeFile.exists()) {
			vcodeFile.mkdirs();
		}
		
		//保存
		savePath += File.separator + cacheFile.getName() + ".jpg";
		vcodeFile = new File(savePath);
		if(vcodeFile.exists()) {
			savePath += "_" + RandomUtils.nextInt(1000);
			vcodeFile = new File(savePath);
		}
		
		FileUtils.copyFile(cacheFile, vcodeFile);
		
		return vcodeFile;
	}
	
}
